package cn.itsource.service;

import cn.hutool.http.HttpUtil;
import cn.itsource.config.WechatConfig;
import cn.itsource.domain.AccessTokenResult;
import cn.itsource.domain.OpenIdResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * @program fccar_240420
 * @Description
 * @Date 2024/09/04 11:20
 * @Version 1.0
 */
public class WechatTemplate {
    private WechatConfig wechatConfig;

    public WechatTemplate(WechatConfig wechatConfig) {
        this.wechatConfig = wechatConfig;
    }

    /**
     * 用来根据code获取openId
     * @param code
     * @return
     */
    public String getOpenId(String code){
        //业务  发送请求到微信获取 openid
        String url = String.format(WechatConfig.WECHAT_URL, wechatConfig.getAppid(), wechatConfig.getSecret(), code);
        //返回的结果 一般都是json数据
        String data = HttpUtil.get(url);
        //变成一个对象
        OpenIdResult openIdResult = JSON.parseObject(data, OpenIdResult.class);
        System.err.println(openIdResult.getOpenid());
        return openIdResult.getOpenid();
    }

    /**
     * 用来根据code获取AccessToken
     * @return
     */
    public String getAccessToken (){
        String accessTokenUrl = String.format(WechatConfig.ACCESS_TOKEN_URL, wechatConfig.getAppid(), wechatConfig.getSecret());
        String data = HttpUtil.get(accessTokenUrl);
        AccessTokenResult accessTokenResult = JSON.parseObject(data, AccessTokenResult.class);
        return accessTokenResult.getAccess_token();
    }

    public String getUserPhone(String phoneCode,String accessToken){
        String userPhoneUrl = String.format(WechatConfig.GET_USER_PHONE_URL, accessToken);
        Map<String, Object> body = new HashMap<>();
        body.put("code",phoneCode);
        String post = HttpUtil.post(userPhoneUrl, body);
        //就是一个map
        JSONObject jsonObject = JSON.parseObject(post);
        JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
        String userPhone = phoneInfo.get("phoneNumber").toString();
        return userPhone;
    }
}
